#!/bin/bash

# 提供双语支持的选择
select_language() {
    echo "请选择您的语言 / Please select your language:"
    echo "1) 中文"
    echo "2) English"
    read -p "输入选项 (1/2): " lang_choice

    case $lang_choice in
        1) LANG="zh";;
        2) LANG="en";;
        *) echo "无效的选择 / Invalid selection."; exit 1;;
    esac
}

# 提升权限或检查权限
if [[ $EUID -ne 0 ]]; then
   if [ "$LANG" == "zh" ]; then
       echo "这个脚本必须以root身份运行。"
   else
       echo "This script must be run as root."
   fi
   exec sudo bash "$0" "$@"
   exit 1
fi

# 检查是否安装了必要的工具
if ! command -v lsblk &> /dev/null || ! command -v numfmt &> /dev/null || ! command -v jq &> /dev/null; then
    if [ "$LANG" == "zh" ]; then
        echo "所需工具（lsblk、numfmt 或 jq）未找到。请确保已安装 util-linux、coreutils 和 jq 包。"
    else
        echo "Required tools (lsblk, numfmt or jq) could not be found. Please ensure util-linux, coreutils and jq packages are installed."
    fi
    exit 1
fi

TIMESHIFT_DIR="/etc/timeshift"
TIMESHIFT_JSON="$TIMESHIFT_DIR/timeshift.json"

# 确保timeshift目录存在
ensure_timeshift_dir() {
    if [ ! -d "$TIMESHIFT_DIR" ]; then
        if ! mkdir -p "$TIMESHIFT_DIR"; then
            if [ "$LANG" == "zh" ]; then
                echo "无法创建目录: $TIMESHIFT_DIR" >&2
            else
                echo "Cannot create directory: $TIMESHIFT_DIR" >&2
            fi
            exit 1
        else
            if [ "$LANG" == "zh" ]; then
                echo "已创建目录: $TIMESHIFT_DIR"
            else
                echo "Directory created: $TIMESHIFT_DIR"
            fi
        fi
    fi
}

# 如果timeshift.json已经存在，则询问是否替换
check_existing_config() {
    if [ -f "$TIMESHIFT_JSON" ]; then
        if [ "$LANG" == "zh" ]; then
            read -p "检测到已存在的配置文件 $TIMESHIFT_JSON，是否要替换？(y/n): " replace_choice
        else
            read -p "Existing configuration file detected at $TIMESHIFT_JSON, do you want to replace it? (y/n): " replace_choice
        fi
        if [[ $replace_choice != [Yy] ]]; then
            if [ "$LANG" == "zh" ]; then
                echo "操作取消。使用现有配置文件：$TIMESHIFT_JSON"
            else
                echo "Operation cancelled. Using existing configuration file: $TIMESHIFT_JSON"
            fi
            exit 0
        fi
    fi
}

# 定义一个关联数组来存储设备信息
declare -A storage_info
declare -A uuids

# 获取并显示所有dm设备、大小、挂载位置及描述，并附带UUID
get_storage_spaces() {
    while IFS= read -r dm; do
        mount_point=$(lsblk -no MOUNTPOINT "$dm" 2>/dev/null)
        size=$(lsblk -b -no SIZE "$dm" 2>/dev/null)
        uuid=$(lsblk -no UUID "$dm" 2>/dev/null)

        if [[ "$mount_point" =~ ^/vol([0-9]+)$ ]] && [ -n "$size" ] && [ -n "$uuid" ]; then
            vol_number=${BASH_REMATCH[1]}
            human_size=$(numfmt --to=iec-i --suffix=B <<< "$size")
            storage_info[$vol_number]="存储空间${vol_number}\t$mount_point\t$human_size"
            uuids[$vol_number]=$uuid
        fi
    done < <(ls -1 /dev/dm-* 2>/dev/null)

    # 输出表头
    if [ "$LANG" == "zh" ]; then
        echo -e "编号\t存储空间\t挂载点\t大小"
    else
        echo -e "Number\tStorage Space\tMount Point\tSize"
    fi

    # 按照挂载点的序号从小到大排序并输出
    for vol_number in $(echo "${!storage_info[@]}" | tr ' ' '\n' | sort -n); do
        echo -e "$vol_number\t${storage_info[$vol_number]}"
    done
}

# 让用户选择一个卷
select_storage_space() {
    if [ "$LANG" == "zh" ]; then
        read -p "请选择一个存储空间（输入编号）: " selected_vol
    else
        read -p "Please select a storage space (enter the number): " selected_vol
    fi

    if [[ -z "${uuids[$selected_vol]}" ]]; then
        if [ "$LANG" == "zh" ]; then
            echo "无效的选择。"
        else
            echo "Invalid selection."
        fi
        exit 1
    fi

    backup_device_uuid="${uuids[$selected_vol]}"
    parent_device_uuid="${uuids[$selected_vol]}"

    if [ "$LANG" == "zh" ]; then
        echo "您选择了存储空间 $selected_vol, UUID: ${backup_device_uuid}"
    else
        echo "You have selected storage space $selected_vol, UUID: ${backup_device_uuid}"
    fi
}

# 中文备份类型描述
declare -A backup_types=(
    ["monthly"]="每月"
    ["weekly"]="每周"
    ["daily"]="每日"
    ["hourly"]="每小时"
    ["boot"]="启动时"
)

# 英文备份类型描述
declare -A backup_types_en=(
    ["monthly"]="Monthly"
    ["weekly"]="Weekly"
    ["daily"]="Daily"
    ["hourly"]="Hourly"
    ["boot"]="Boot"
)

# 交互获取备份规律设置，使用中文提示，并确保输出的JSON值被引号包围
get_schedule_settings() {
    local schedule=()
    for type in "${!backup_types[@]}"; do
        while true; do
            if [ "$LANG" == "zh" ]; then
                read -p "您想要启用${backup_types[$type]}备份吗？(y/n): " choice
            else
                read -p "Do you want to enable ${backup_types_en[$type]} backups? (y/n): " choice
            fi
            case $choice in
                [Yy]* )
                    while true; do
                        if [ "$LANG" == "zh" ]; then
                            read -p "您想要保留多少个${backup_types[$type]}快照？ " count
                        else
                            read -p "How many ${backup_types_en[$type]} snapshots do you want to keep? " count
                        fi
                        if [[ "$count" =~ ^[0-9]+$ ]]; then
                            schedule+=("\"schedule_$type\": \"true\", \"count_$type\": \"$count\"")
                            break
                        else
                            if [ "$LANG" == "zh" ]; then
                                echo "请输入一个有效的数字: "
                            else
                                echo "Please enter a valid number: "
                            fi
                        fi
                    done
                    break
                    ;;
                [Nn]* )
                    schedule+=("\"schedule_$type\": \"false\", \"count_$type\": \"0\"")
                    break
                    ;;
                * )
                    if [ "$LANG" == "zh" ]; then
                        echo "请回答 yes 或 no."
                    else
                        echo "Please answer yes or no."
                    fi
                    ;;
            esac
        done
    done
    echo "{$(IFS=,; echo "${schedule[*]}")}"
}

# 获取根目录下以"vol"开头的文件夹
get_vol_folders() {
    local vol_folders=()
    shopt -s nullglob
    for item in /vol*/; do
        if [ -d "$item" ]; then
            item=$(echo "$item" | sed 's|/$||')
            vol_folders+=("\"$item/**\"")
        else
            if [ "$LANG" == "zh" ]; then
                echo "无法访问 '$item' 目录。" >&2
            else
                echo "Unable to access directory '$item'." >&2
            fi
        fi
    done
    printf '[%s]\n' "$(IFS=,; echo "${vol_folders[*]}")"
}

# 更新timeshift.json文件
update_timeshift_json() {
    local exclude=$(get_vol_folders)
    local schedule=$(get_schedule_settings)

    # 验证 JSON 格式
    if ! jq -e . <<< "$schedule" &> /dev/null; then
        if [ "$LANG" == "zh" ]; then
            echo "调度设置 JSON 格式无效: $schedule" >&2
        else
            echo "Invalid JSON format for schedule settings: $schedule" >&2
        fi
        return 1
    fi

    if ! jq -e . <<< "$exclude" &> /dev/null; then
        if [ "$LANG" == "zh" ]; then
            echo "排除目录 JSON 格式无效: $exclude" >&2
        else
            echo "Invalid JSON format for exclude directories: $exclude" >&2
        fi
        return 1
    fi

    # 构建基础 JSON 配置，并包含传入的UUID，同时确保所有布尔值作为字符串处理
    base_json=$(jq -n \
        --arg bd_uuid "$backup_device_uuid" \
        '
        {
            backup_device_uuid: $bd_uuid,
            do_first_run: "false",
            btrfs_mode: "false",
            include_btrfs_home_for_backup: "false",
            include_btrfs_home_for_restore: "false",
            stop_cron_emails: "false",
            date_format: "%Y-%m-%d %H:%M:%S",
            "exclude-apps": [],
            exclude: ["/media/**", "/share/**", "/var/log/**", "/fs/**"]
        }')

    combined_json=$(jq --argjson s "$schedule" '. * $s' <<< "$base_json")
    final_json=$(jq --argjson ex "$exclude" '.exclude |= . + $ex' <<< "$combined_json")

    # 写入最终 JSON 配置
    echo "$final_json" > "$TIMESHIFT_JSON"

    if [ "$LANG" == "zh" ]; then
        echo "配置已写入 $TIMESHIFT_JSON"
    else
        echo "Configuration has been written to $TIMESHIFT_JSON"
    fi
}

# 检查并安装timeshift工具，隐藏安装过程的输出
install_timeshift() {
    if ! command -v timeshift &> /dev/null; then
        if [ "$LANG" == "zh" ]; then
            echo -n "正在安装 Timeshift..."
        else
            echo -n "Installing Timeshift..."
        fi
        apt-get update -qq && apt-get install -y timeshift > /dev/null 2>&1
        if [ $? -eq 0 ]; then
            if [ "$LANG" == "zh" ]; then
                echo "完成"
            else
                echo "Done"
            fi
        else
            if [ "$LANG" == "zh" ]; then
                echo "失败，请自行检查"
            else
                echo "Failed, please check manually"
            fi
            exit 1
        fi
    else
        if [ "$LANG" == "zh" ]; then
            echo "Timeshift 已安装。"
        else
            echo "Timeshift is already installed."
        fi
    fi
}

# 创建快照并隐藏输出，展示简单的等待消息
create_snapshot() {
    if [ "$LANG" == "zh" ]; then
        echo "正在创建快照，请耐心等待，预计用时1-5分钟..."
    else
        echo "Creating a snapshot, please wait patiently, estimated time 1-5 minutes..."
    fi
    
    # 执行快照创建命令并将输出重定向到日志文件
    if sudo timeshift --check > /tmp/timeshift.log 2>&1; then
        if [ "$LANG" == "zh" ]; then
            echo "快照创建成功！"
        else
            echo "Snapshot created successfully!"
        fi
    else
        if [ "$LANG" == "zh" ]; then
            echo "快照创建过程中出现错误，请检查日志。"
        else
            echo "An error occurred during snapshot creation, please check the log."
        fi
        cat /tmp/timeshift.log
        exit 1
    fi
}

# 主函数
main() {
    select_language
    ensure_timeshift_dir
    check_existing_config
    get_storage_spaces
    select_storage_space
    update_timeshift_json
    install_timeshift
    create_snapshot
    
    if [ "$LANG" == "zh" ]; then
        read -p "按任意键退出..." -n1 -s
    else
        read -p "Press any key to exit..." -n1 -s
    fi
    echo
}

# 执行主函数
main
